<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button
            class="filter-item marginRB10"
            type="success"
            @click="handleCreate()"
          >&emsp;新增&emsp;
          </el-button>
          <el-button class="marginRB10" type="danger" @click="allDel()"
          >批量删除
          </el-button
          >
          <el-select
            v-model="listQuery.sold"
            class="filter-item marginRB10"
            filterable
            placeholder="请选择状态"
            style="width: 200px"
          >
            <el-option
              v-for="item in selectList"
              :key="item.key"
              :label="item.lab"
              :value="item.key"
            ></el-option>
          </el-select>
          <el-select
            v-model="listQuery.type"
            class="filter-item marginRB10"
            filterable
            placeholder="请选择类别"
            style="width: 200px"
          >
            <el-option
              v-for="item in selectList2"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-input
            v-model="listQuery.name"
            class="marginRB10"
            clearable
            placeholder="请输入礼物名称"
            style="width: 200px"
          ></el-input>
          <el-button
            class="marginRB10"
            icon="el-icon-search"
            type="primary"
            @click="searchForm"
          >搜索
          </el-button>
        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table
          ref="dataList"
          :data="menuList"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          row-key="id"
          style="margin-bottom: 20px"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="序号" prop="id"></el-table-column>
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="图片" prop="picture">
            <template slot-scope="scope">
              <el-popover max-width="220" placement="right" trigger="hover">
                <img
                  :src="scope.row.picture"
                  alt=""
                  style="max-width: 200px; max-height: 200px"
                />
                <img
                  slot="reference"
                  :src="scope.row.picture"
                  alt=""
                  style="width: 50px"
                />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="效果" prop="special">
            <template slot-scope="scope">
              <div v-if="/.mp4$/.test(scope.row.special)">
                <el-popover max-width="220" placement="right" trigger="hover">
                  <video
                    :src="scope.row.special"
                    controls
                    style="max-width:200px"
                  ></video>
                  <video
                    slot="reference"
                    :src="scope.row.special"
                    autoplay
                    loop
                    muted
                    style="width: 50px;"
                  ></video>
                </el-popover>
              </div>
              <div v-else-if="/.webp$/.test(scope.row.special)">
                <el-popover max-width="220" placement="right" trigger="hover">
                  <img
                    :src="scope.row.special"
                    alt=""
                    style="max-width: 200px; max-height: 200px"
                  />
                  <img
                    slot="reference"
                    :src="scope.row.special"
                    alt=""
                    style="width: 50px"
                  />
                </el-popover>
              </div>
              <div v-else-if="/.svga$/.test(scope.row.special)">
                <el-popover max-width="220" placement="right" trigger="hover">
                  <!-- <svga :src="scope.row.special" :options="options"> -->
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="礼物框" prop="gift_frame.name"/>
          <el-table-column label="价格" prop="price"></el-table-column>
          <el-table-column label="心动值" prop="cardiac"></el-table-column>
          <el-table-column label="类别" prop="type_name"></el-table-column>
          <el-table-column label="状态" prop="sold">
            <template slot-scope="scope">
              {{ scope.row.sold === 1 ? '上架' : '下架' }}
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="sort"></el-table-column>

          <el-table-column label="操作" width="260">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                plain
                size="mini"
                type="primary"
                @click="handleUpdate(scope.row)"
              >编辑
              </el-button>
              <el-button
                v-if="scope.row.sold === 2"
                plain
                size="mini"
                type="success"
                @click="upDown(scope.row, 1)"
              >上架
              </el-button>
              <el-button
                v-if="scope.row.sold === 1"
                plain
                size="mini"
                type="warning"
                @click="upDown(scope.row, 2)"
              >下架
              </el-button>
              <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          v-show="total > 0"
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>

    <el-dialog
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :model="form"
        :rules="rules"
        label-position="right"
        label-width="80px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="form.name"
            maxlength="30"
            placeholder="请输入名称"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="图片" prop="picture">
          <el-upload
            :auto-upload="true"
            :before-upload="handleBeforeUploadPicture"
            :file-list="pictureList"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handlePropPictureRemove"
            :on-success="handlePropPictureSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">
              上传图片
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="特效">
          <el-upload
            :auto-upload="true"
            :before-upload="handleBeforeUploadSpecial"
            :file-list="specialList"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove"
            :on-success="handleSpecialFlagBigSuccess"
            action=""
            class="upload-demo"
            list-type="text"
          >
            <el-button slot="trigger" size="small" type="primary"
            >上传特效
            </el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="心动值" prop="cardiac">
          <el-input v-model="form.cardiac" placeholder="请输入心动值"/>
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-select
            v-model="form.type"
            class="filter-item"
            filterable
            placeholder="请选择类别"
            style="width: 280px"
          >
            <el-option
              v-for="item in selectList3"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="礼物框" prop="frame_id">-->
        <!--          <el-select-->
        <!--            v-model="form.frame_id"-->
        <!--            class="filter-item"-->
        <!--            filterable-->
        <!--            placeholder="请选择礼物框"-->
        <!--            style="width: 280px"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in selectList4"-->
        <!--              :key="item.id"-->
        <!--              :label="item.name"-->
        <!--              :value="item.id"-->
        <!--            ></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="排序">
          <el-input v-model="form.sort" placeholder="请输入排序"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, listData, saveData, typeList, updateData, upDowmData } from '@/api/giftMem/giftList'

export default {
  data() {
    return {

      options: {
        loop: 0,
        fillMode: 'forwards',
        playMode: 'forwards',
        startFrame: 0,
        endFrame: 0,
        autoPlay: true
      },

      confirmBtn: false,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10
      },
      selectList: [
        { key: undefined, lab: '全部上架状态' },
        { key: '1', lab: '上架' },
        { key: '2', lab: '下架' }
      ],
      selectList2: [],
      selectList3: [],
      // selectList4: [],
      menuList: [
        {
          id: '1',
          name: '1',
          picture: '1',
          special: '1',
          price: '1',
          type: '1',
          sold: '1',
          sort: '1'
        }
      ],
      dialogFormVisible: false,
      dialogStatus: '',
      titleMap: {
        update: '编辑',
        create: '增加'
      },

      pictureList: [],
      specialList: [],
      form: {
        id: undefined,
        name: undefined,
        picture: undefined,
        special: undefined,
        price: '',
        cardiac: '',
        type: undefined,
        sold: undefined,
        sort: undefined,
        frame_id: 0
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: 'blur'
          }
        ],
        picture: [{ required: true, message: '请输入图片', trigger: 'change' }],
        special: [{ required: true, message: '请输入效果', trigger: 'change' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        cardiac: [{ required: true, message: '请输入心动值', trigger: 'blur' }],
        type: [{ required: true, message: '请输入类别', trigger: 'blur' }]
        // frame_id: [{ required: true, message: '请输入礼物框', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getTypeList()
    // this.getGiftWallList()
  },
  methods: {
    searchForm() {
      this.listQuery.page = 1
      this.getList()
    },
    handleBeforeUploadPicture(file) {
      const isPic =
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/webp'
      const isLt2M = file.size / 1024 / 1024 < 4
      if (!isPic) {
        this.$message.error('请上传图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 4MB!')
      }
      return isPic && isLt2M
    },
    handleBeforeUploadSpecial(file) {
      const isMp4 = file.type === 'video/mp4'
      if (!isMp4) {
        this.$message.error('上传特效只能为 MP4 格式!')
      }
      return isMp4
    },
    handleChangePic(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handlePropPictureSuccess() {
      this.form.picture = this.ossLastImgUrl
      this.pictureList = [{ url: this.ossLastImgUrl }]
    },
    handlePropPictureRemove(res) {
      this.form.picture = undefined
      this.pictureList = []
    },
    handleSpecialFlagBigSuccess() {
      this.form.special = this.ossLastImgUrl
      this.specialList = [{ name: this.ossLastImgUrl }]
    },
    handleSpecialFlagBigRemove() {
      this.form.special = undefined
      this.specialList = []
    },

    handleAvatarSuccess(res, file) {
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      this.form.picture = file
    },
    handleAvatarSuccess2(res, file) {
    },
    beforeAvatarUpload2(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      this.form.special = file
      // return isJPG && isLt2M;
    },
    getTypeList() {
      typeList().then(response => {
        this.selectList2 = [
          { id: undefined, name: '全部分类' },
          ...response.data
        ]
        this.selectList3 = response.data
      })
    },
    getList() {
      this.listLoading = true
      listData(this.listQuery).then(response => {
        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
        this.confirmBtn = false
      })
    },
    // getGiftWallList() {
    //   listGiftWallData(`?page=1&perPage=10000`).then(res => {
    //     res.data.list.forEach(item => {
    //       this.selectList4.push({ id: item.id, name: item.name })
    //     })
    //   })
    // },
    handleCreate(row) {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.specialList = []
      this.pictureList = []
      this.form = []
      this.form.id = row.id
      this.form.name = row.name
      this.form.picture = row.picture
      if (row.picture) {
        this.pictureList = [{ url: row.picture }]
      }
      this.form.special = row.special
      if (row.special) {
        this.specialList = [{ name: row.special }]
      }
      this.form.price = row.price
      this.form.cardiac = row.cardiac
      this.form.type = row.type
      // this.form.sold= row.sold
      this.form.sort = row.sort
      this.form.frame_id = 0

      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      this.form = Object.assign({}, this.form)
    },
    handleDelete(row) {
      if (this.confirmBtn) return
      this.confirmBtn = true
      let data = { ids: row.id }
      deleteData(data).then(response => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
        }
      })
    },
    allDel() {
      if (this.confirmBtn) return
      this.confirmBtn = true
      let delNum = []
      this.$refs.dataList.selection.forEach(k => {
        delNum.push(k.id)
      })
      if (delNum.length === 0) {
        return
      }
      let data = { ids: delNum.toString() }
      deleteData(data).then(response => {
        if (response.code === 200) {
          this.getList()
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
        }
      })
    },
    submitForm() {
      if (this.confirmBtn) return

      // return;
      this.$refs['dataForm'].validate(valid => {
        if (valid && this.dialogStatus === 'create') {
          this.confirmBtn = true
          // let formData = new FormData()
          // for (let item in this.form) {
          //   this.form[item] === undefined
          //     ? ''
          //     : formData.append(item, this.form[item])
          // }
          saveData(this.form).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
              this.dialogFormVisible = false
            } else {
              this.confirmBtn = false
            }
          })
        } else if (valid && this.dialogStatus === 'update') {
          this.confirmBtn = true
          let formData = new FormData()
          for (let item in this.form) {
            // this.form[item] === undefined ? "" : formData.append(item, this.form[item]);
            if (this.form[item] !== undefined && this.form[item] !== '') {
              formData.append(item, this.form[item])
            }
          }

          updateData(formData).then(response => {
            if (response.code === 200) {
              this.getList()
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              })
              this.dialogFormVisible = false
            } else {
              this.confirmBtn = false
            }
          })
        }
      })
    },
    upDown(row, type) {
      let data = { id: row.id, sold: type }
      upDowmData(data).then(response => {
        if (response.code === 200) {
          this.getList()
          this.submitOk('操作成功')
        } else {
          this.submitFail('操作失败')
        }
      })
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: undefined,
        picture: undefined,
        special: undefined,
        price: undefined,
        cardiac: undefined,
        type: undefined,
        sold: undefined,
        sort: undefined,
        frame_id: 0
      }
      this.pictureList = []
      this.specialList = []
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>
<style scoped>
/deep/ .el-upload-list__item {
  transition : none !important;
}

/deep/ .el-upload-list--picture {
  max-height : 103px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list--text {
  max-height : 100px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list__item-name {
  white-space : normal !important;
}
</style>
